package com.wisdytech.linkdcs.equipLifeCycle.maintain.service.impl;

import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.*;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.*;
import com.wisdytech.linkdcs.partLife.dto.PartReplaceDTO;
import com.wisdytech.linkdcs.partLife.model.KeyPart;
import com.wisdytech.linkdcs.partLife.model.ModelPart;
import com.wisdytech.linkdcs.partLife.model.Part;
import com.wisdytech.linkdcs.partLife.service.IPartReplaceService;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.service.ITPReplaceTempService;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.MaintenanceItemRecordDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.MaintenanceTaskDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.TeskResultDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenanceRecordService;
import com.wisdytech.linkdcs.equipLifeCycle.malfunction.model.TPReplaceTemp;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.model.EqToolConfig;
import com.wisdytech.linkdcs.tool.service.IEqToolConfigService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.wisdytech.linkdcs.partLife.service.IKeyPartService;
import com.wisdytech.linkdcs.partLife.service.IModelPartService;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.service.IEquipmentRegisteredService;
import javax.annotation.Resource;
import com.wisdytech.linkdcs.partLife.service.IPartService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-06-19
 */
@Service("iMaintenanceRecordService")
@Transactional
public class MaintenanceRecordServiceImpl extends BaseService<IMaintenanceRecordDao, MaintenanceRecord> implements IMaintenanceRecordService {

	@Resource
	private IMaintenanceRecordDao iMaintenanceRecordDao;
	@Resource
	private IMaintenanceDetailDao iMaintenanceDetailDao;
    @Resource
    private IMaintenanceItemDao iMaintenanceItemDao;
	@Resource
	private IMaintenanceTaskDao iMaintenanceTaskDao;
	@Resource
	private IMaintenancePlanDao iMaintenancePlanDao;
	@Resource
	private ITPReplaceTempService iTPReplaceTempService;
	@Resource
	private IPartReplaceService iPartReplaceService;
	@Resource
	private IEquipmentRegisteredService equipmentRegisterService;
	@Resource
	private IPartService iPartService;
	@Resource
	private IKeyPartService iKeyPartService;
	@Resource
	private IModelPartService iModelPartService;
	@Resource
	private IEqToolConfigService iEqToolConfigService;

    /**
     * 注入设备dao
     */
    @Resource
    private IEqEquipmentDao eqEquipmentDao;
	@Override
	public void saveTeskResult(List<TeskResultDTO> list) {
		//获取设备id
		String equipId = null;
		for(TeskResultDTO teskResultDTO :list ) {
			Equipment eq = new Equipment();
			eq.setEquipCode(teskResultDTO.getEquipCode());
//			Equipment equipment = equipmentRegisterService.getEquipmentByEquipCode(teskResultDTO.getEquipCode());
			Equipment equipment = eqEquipmentDao.selectOne(eq);
			equipId = equipment.getPkId();
		}		
		//查询该条保养计划
		String taskId = null;
		for(TeskResultDTO teskResultDTO :list ) {
			taskId = teskResultDTO.getTaskId();
		}
		MaintenanceTask maintenanceTask = iMaintenanceTaskDao.selectById(taskId);
		MaintenancePlan maintenancePlan = iMaintenancePlanDao.selectById(maintenanceTask.getPlanId());
		//更改任务的状态
		//临时任务
		if(maintenanceTask.getType().equals(CommonConstants.INTERI_TASK)) {
			maintenanceTask.setTaskStatus(CommonConstants.TASK_YES);//改为已保养状态
			iMaintenanceTaskDao.updateById(maintenanceTask);
		}
		//周期性任务
		if(maintenanceTask.getType().equals(CommonConstants.CYCLE_TASK)) {
			//生成下一条保养任务
			//修改保养时间
		 	Date nowDate = new Date();
		 	maintenanceTask.setLastDate(nowDate);//生成上次保养时间
		 	Calendar c = Calendar.getInstance();  
		 	c.setTime(nowDate);  
		 	c.add(Calendar.DAY_OF_MONTH, (int)Math.round(maintenancePlan.getMaintainCycle()));//增加时间
		 	Date nextDate = c.getTime();  
			maintenanceTask.setNextDate(nextDate);//下次保养时间
			maintenanceTask.setDelFlag(CommonConstants.DEL_FLAG_TRUE);//标记为已保养过
			iMaintenanceTaskDao.updateById(maintenanceTask);
		}
		
		//生成保养记录
		MaintenanceRecord maintenanceRecord = new MaintenanceRecord();
		String pkId = BaseUtil.getUUID();
		maintenanceRecord.setPkId(pkId);
		for(TeskResultDTO teskResultDTO:list) {
			maintenanceRecord.setMaintainTimeSpan(teskResultDTO.getMaintainTimeSpan());//总耗时
			maintenanceRecord.setTaskId(teskResultDTO.getTaskId());//保养任务
			//判断是否需要确认
			if(maintenancePlan.getMaintainConfirm()==0.0) {
				maintenanceRecord.setStatus(0.0);//该记录为待确认状态
			}
			if(maintenancePlan.getMaintainConfirm()==1.0) {
				maintenanceRecord.setStatus(1.0);//该记录已完成状态
			}
		}
		maintenanceRecord.setDelFlag(CommonConstants.DEL_FLAG);
		maintenanceRecord.setCreateDate(new Date());//保养时间
	    SysUser userSession = BaseUtil.getCurrentUser();
	    String loginName = userSession.getTruename();
		maintenanceRecord.setCreateUser(loginName);//保养人
		iMaintenanceRecordDao.insert(maintenanceRecord);
		//保存保养明细
		MaintenanceDetail maintenanceDetail = new MaintenanceDetail();
		for(TeskResultDTO teskResultDTO : list) {
            maintenanceDetail.setPkId(BaseUtil.getUUID());
            maintenanceDetail.setRecordId(pkId);
            MaintenanceItem i = new MaintenanceItem();
            i.setItemCode(teskResultDTO.getItemCode());
            MaintenanceItem item = this.iMaintenanceItemDao.selectOne(i);
            maintenanceDetail.setItemId(item.getVersion());
            maintenanceDetail.setMaintenanceResult(teskResultDTO.getMaintenanceResult());
            iMaintenanceDetailDao.insert(maintenanceDetail);
        }
		
		//同步更新备件及工装更换-将信息更改为已经已确定
		Filter filter = new Filter();
		filter.setSize(65533);
		PageInfo<TPReplaceTemp> temps =this.iTPReplaceTempService.getTemps(filter, taskId);
		List<TPReplaceTemp> templist = temps.getList();
		if(!templist.isEmpty()) {
			for(TPReplaceTemp tPReplaceTemp :templist) {
				tPReplaceTemp.setRecordId(pkId);
				tPReplaceTemp.setFlag("1");
				this.iTPReplaceTempService.update(tPReplaceTemp);
			}
			//同步更换信息
			this.savePartReplace(templist,equipId);
		}
	}
	@Override
	public PageInfo<MaintenanceRecord> listTaskRecordByFilter(MaintenanceTaskDTO taskDTO, Filter filter,
			String loginName) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("equipCode", taskDTO.getEquipCode());
        queryMap.put("equipName", taskDTO.getEquipName());
        queryMap.put("supplier",taskDTO.getSupplier());
        queryMap.put("modelType", taskDTO.getModelType());
        queryMap.put("startTime", taskDTO.getStartTime());
        String endTime = taskDTO.getEndTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date time = sdf.parse(endTime);
			long numTime = time.getTime()+24*60*60*1000;
			Date date = new Date(numTime);
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
			String lastTime = sd.format(date);
			queryMap.put("endTime", lastTime);
		} catch (Exception e) {
			e.printStackTrace();
		}

        queryMap.put("maintainCycle", taskDTO.getMaintainCycle());
        List<MaintenanceRecord> lists =
                super.beforeList(IMaintenanceRecordDao.class, filter).listTaskRecordByFilter(queryMap);
        PageInfo<MaintenanceRecord> page=new PageInfo<>(lists);
        return page;
	}
	@Override
	public PageInfo<MaintenanceRecord> listTaskConfirmByFilter(MaintenanceTaskDTO taskDTO, Filter filter,
			String loginName) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("equipCode", taskDTO.getEquipCode());
        queryMap.put("equipName", taskDTO.getEquipName());
        queryMap.put("supplier",taskDTO.getSupplier());
        queryMap.put("modelType", taskDTO.getModelType());
        queryMap.put("startTime", taskDTO.getStartTime());
        queryMap.put("endTime", taskDTO.getEndTime());
        List<MaintenanceRecord> lists =
                super.beforeList(IMaintenanceRecordDao.class, filter).listTaskConfirmByFilter(queryMap);
        PageInfo<MaintenanceRecord> page=new PageInfo<>(lists);
        return page;
	}
	@Override
	public void saveTeskConfirmResult(String confirmResult,String pkId) {
		MaintenanceRecord maintenanceRecord = iMaintenanceRecordDao.selectById(pkId);
		maintenanceRecord.setConfirmDate(new Date());//确认时间
		maintenanceRecord.setConfirmResult(Double.parseDouble(confirmResult));
        SysUser userSession = BaseUtil.getCurrentUser();
        String loginName = userSession.getTruename();
		maintenanceRecord.setConfirmUser(loginName);
		maintenanceRecord.setStatus(1.0);//将状态改为已确认（已完成）
		iMaintenanceRecordDao.updateById(maintenanceRecord);
	}
	
	private void savePartReplace(List<TPReplaceTemp> templist,String equipId) {
		for(TPReplaceTemp tPReplaceTemp : templist) {
			//更换备件
			if(tPReplaceTemp.getType().equals("0")) {
				this.savePartRep(equipId, tPReplaceTemp);
			}
			//更换工装
			if(tPReplaceTemp.getType().equals("1")) {
				this.saveToolRep(equipId,tPReplaceTemp);
			}
		}
	}
	//同步工装的更换
	private void saveToolRep(String equipId, TPReplaceTemp tPReplaceTemp) {
		SysUser user = BaseUtil.getCurrentUser();
		EqToolConfig eqToolConfig = new EqToolConfig();
		//报修
		if(tPReplaceTemp.getUseFlag().equals("0")) {
			eqToolConfig.setRepair("1");
		}
		//报废
		if(tPReplaceTemp.getUseFlag().equals("1")) {
			eqToolConfig.setScrap("1");
		}
		//可使用
		if(tPReplaceTemp.getUseFlag().equals("2")) {
			eqToolConfig.setRepair("2");
			eqToolConfig.setScrap("2");
		}
		eqToolConfig.setToolCode(tPReplaceTemp.getCode());//新编码
		eqToolConfig.setOriginToolCode(tPReplaceTemp.getoCode());//原编码
		eqToolConfig.setReplaceDate(new Date());
		eqToolConfig.setReplaceReason("保养");
		eqToolConfig.setReplaceUser(user.getUsername());
		eqToolConfig.setEquipPosition(tPReplaceTemp.getLocationCode());//工装位置
        Equipment equipment = eqEquipmentDao.selectById(equipId);
        eqToolConfig.setEquipCode(equipment.getEquipCode());
		this.iEqToolConfigService.replaceToolTemp(eqToolConfig, user,equipId);
		
	}
	//同步备件更换
	private void savePartRep(String equipId,TPReplaceTemp tPReplaceTemp) {
		PartReplaceDTO partReplacedto = new PartReplaceDTO();
		partReplacedto.setEquipId(equipId);
		//获取备件型号信息
		Part part =iPartService.getPartByPartCode(tPReplaceTemp.getCode());
		ModelPart modelPart = iModelPartService.getModelPartIdByPkIdAndEqId(tPReplaceTemp.getLocationCode());
		partReplacedto.setPartId(modelPart.getPkId());
		if(part.getKeyPartFlag()!=null) {
			partReplacedto.setKeyPartFlag(part.getKeyPartFlag().toString());
		}
		KeyPart keyPartn = null;
		if(StringUtils.isNotBlank(tPReplaceTemp.getnSerialNum())) {
			keyPartn = iKeyPartService.getKeyPartByOseri(tPReplaceTemp.getnSerialNum());
			partReplacedto.setnSerialNum(keyPartn.getPkId());
		}
		//通过序列号查找对应关键备件
		if(StringUtils.isNotBlank(tPReplaceTemp.getoSerialNum())) {
			//为不是第一次更换
			KeyPart keyParto = iKeyPartService.getKeyPartByOseri(tPReplaceTemp.getoSerialNum());
			partReplacedto.setoSerialNum(keyParto.getPkId());
		}

	    SysUser userSession = BaseUtil.getCurrentUser();
	    String userId = userSession.getPkId();
	    partReplacedto.setRepUser(userId);
	    partReplacedto.setRepReason("保养");
	    partReplacedto.setRepNum(tPReplaceTemp.getNum());
	    if(tPReplaceTemp.getUseFlag() != null && tPReplaceTemp.getUseFlag()!="") {
	    	partReplacedto.setStatus(Double.parseDouble(tPReplaceTemp.getUseFlag()));
	    }
	    iPartReplaceService.savePartReplaceTemp(partReplacedto);
	}
	@Override
	public PageInfo<MaintenanceRecord> listItemRecordByFilter(MaintenanceItemRecordDTO itemDTO, Filter filter) {
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("equipCode", itemDTO.getEquipCode());
        queryMap.put("equipName", itemDTO.getEquipName());
        queryMap.put("typeName",itemDTO.getTypeName());
        queryMap.put("itemName", itemDTO.getItemName());
        queryMap.put("startTime", itemDTO.getStartTime());
        queryMap.put("endTime", itemDTO.getEndTime());
        List<MaintenanceRecord> lists =
                super.beforeList(IMaintenanceRecordDao.class, filter).listItemRecordByFilter(queryMap);
        PageInfo<MaintenanceRecord> page=new PageInfo<>(lists);
        return page;
	}
}
